﻿#include "projectfilewatcher.h"

#include <QFile>
#include <QDir>
#include <QStandardPaths>
#include <QJsonArray>

ProjectFileWatcher::ProjectFileWatcher(QObject *parent)
    : QObject{parent}
{
    initialize();
}

void ProjectFileWatcher::initialize()
{
    const QString watcherDirPath =
        QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/watcher";
    this->_defDirPath = watcherDirPath;

    const QDir watcherDir(watcherDirPath);
    if (!watcherDir.exists()) {
        watcherDir.mkpath(watcherDirPath);
    }
}

QString ProjectFileWatcher::getFileFullPathByPid(const QString &pid)
{
    return this->_defDirPath + "/" + pid + ".json";
}

bool ProjectFileWatcher::existsByPid(const QString &pid)
{
    return QFile::exists(getFileFullPathByPid(pid));
}

QString ProjectFileWatcher::readFileDataByPid(const QString &pid)
{
    QString content;
    QFile file(getFileFullPathByPid(pid));
    if (file.open(QIODevice::ReadOnly)) {
        QTextStream stream(&file);
        content = stream.readAll();
    }
    return content;
}

bool ProjectFileWatcher::writeFileDataByPid(const QString &pid, const QString &data)
{
    QFile file(getFileFullPathByPid(pid));
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream stream(&file);
        stream << data;
    }
    return true;
}

bool ProjectFileWatcher::exists(const QString &fileName)
{
    return QFile::exists(fileName);
}

bool ProjectFileWatcher::removeByPid(const QString &pid)
{
    QFile file(getFileFullPathByPid(pid));
    return file.remove();
}
